#include <cassert>
#include <iostream>
#include <string>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>

#include <leveldb/db.h>
bool exec_cmdstr(const char *cmdstr){
    FILE *fp = popen(cmdstr, "r");
    if(fp == NULL){
        printf("execute %s failed.\n", cmdstr);
        pclose(fp);
        return false;
    }
    char buf[200] = {0};
    while(NULL != fgets(buf, sizeof(buf), fp)){
        if( strpbrk(buf, "Connection timed out") ){
            fprintf(stdout, "Error: Connection timed out.");
            return false;
        }
    }   
    pclose(fp);
    return true;
}

int main() {
    int ret;
    //ret = execl("/usr/bin/scp", "scp", "-P", "11022", "-r", "-v", "/home/a.log", "xiesunway@221.234.43.214:/home/xiesunway", NULL);  
    std::string cmdstr;
    cmdstr = "/usr/bin/ssh -p 11022 -v bytweb@221.234.43.214 mkdir /home/mytest/ttt";
    exec_cmdstr(cmdstr.c_str());
    printf("ret: %d\n", ret);
    return 1;
    pid_t pid = fork();
    
    if( pid == 0 ){
        std::string cmdstr;
        cmdstr.append("/usr/bin/scp -P 11022 -r /home/a.log xiesunway@221.234.43.214:/home/xiesunway");
        std::cout << cmdstr << std::endl;
        printf("cmd str: %s\n", cmdstr.c_str());
        exec_cmdstr(cmdstr.c_str());
    }
    
    leveldb::DB *db;
    leveldb::Options options;
    leveldb::Status status;

    std::string key1 = "key1";
    std::string val1 = "val1 hello world...", val;
    std::string key2 = "221.234.43.214";
    std::string val2 = "SYNC";

    options.create_if_missing = true;
    status = leveldb::DB::Open(options, "/tmp/testdb", &db);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        exit(1);
    }

    status = db->Put(leveldb::WriteOptions(), key1, val1);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        exit(2);
    }

    status = db->Get(leveldb::ReadOptions(), key1, &val);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        exit(3);
    }
    std::cout << "Get val: " << val << std::endl;
    
    status = db->Put(leveldb::WriteOptions(), key2, val2);
    if(!status.ok()){
        exit(4);
    }

    status = db->Get(leveldb::ReadOptions(), key2, &val);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        exit(5);
    }
    std::cout << "Get val: " << val << std::endl;

    leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
    for (it->SeekToFirst(); it->Valid(); it->Next()) {
        std::cout << it->key().ToString() << ": " << it->value().ToString() << std::endl;
    }
    assert(it->status().ok()); // Check for any errors found during the scan

    status = db->Delete(leveldb::WriteOptions(), key1);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        exit(6);
    }

    delete it;
    return 0;
}
